package org.anderes.osgi.sample.hello.consumer;

import org.anderes.osgi.sample.hello.provider.IHelloProvider;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

public class Activator implements BundleActivator {

	private ServiceTracker helloProviderTracker;

	public void start(final BundleContext context) {
		
		helloProviderTracker = new ServiceTracker(context, IHelloProvider.class.getName(),
				new ServiceTrackerCustomizer() {

			public Object addingService(final ServiceReference reference) {
				final IHelloProvider helloProvider = (IHelloProvider) context
						.getService(reference);
				System.out.println(helloProvider.sayHello());
				return helloProvider;
			}

			public void modifiedService(final ServiceReference reference,
					final Object service) { // Nothing to be done!
			}

			public void removedService(final ServiceReference reference,
					final Object service) { // Nothing to be done!
			}
		});
		helloProviderTracker.open();
	}

	public void stop(final BundleContext context) {
		if (helloProviderTracker != null)
			helloProviderTracker.close();
	}
}